#!/usr/bin/env Rscript
if (!require("librarian", quietly = TRUE))
  install.packages("librarian")
library(librarian)
shelf(argparse, readr, tibble, dplyr, stringr, purrr, httr2, crayon)

query_unichem_src <- function(zinc.id) {
  require(httr2)
  req <- request("https://www.ebi.ac.uk/unichem/api/v1/compounds") |>
    req_headers("Accept" = "application/json") |>
    req_body_json(list(compound = zinc.id, sourceID = 9,
                       type = "sourceID"))
  resp <- req_perform(req)
  resp.lst <- resp |> resp_body_json(simplifyVector = T)
  resp.lst$compounds$sources[[1]] |> as_tibble() |>
    select(compoundId, shortName, url)
}

parser <- ArgumentParser()

parser$add_argument("-i", "--input", nargs = "+", help = "Input tsv file with zinc_id column, REQUIRED")
parser$add_argument("-o", "--output",
                    help = "Output prefix, REQUIRED"
)

input_args <- parser$parse_args()

unichem <- input_args$input |>
  read_tsv() |>
  pull(zinc_id) |>
  unique() |>
  set_names() |>
  map(safely(query_unichem_src), .progress = T) |>
  list_transpose(simplify = F) |>
  pluck('result') |>
  list_rbind(names_to = 'zinc_id') |>
  mutate(nsrc = n(), .by = zinc_id)

unichem |>
  write_csv(input_args$output)

cb.name <- sub('csv$', 'domestic.csv', input_args$output)

unichem |>
  filter(shortName == 'chemicalbook' | nsrc >= 10) |>
  write_csv(cb.name)